using System;
using System.Collections.Generic;
using System.Linq;

namespace PokerStar.Core.Rules
{
    public class StraightRule : BasicRule
    {
        public StraightRule(IRule next)
            : base(next)
        {
        }

        protected override GameResult Match(RuleContext context)
        {
            if (context.GroupByNumber.Length >= 5)
            {
                var cards = context.GroupByNumber.
                    Select(p => p.First()).
                    OrderByDescending(p => p.Number, new CardNumberComparer()).
                    ToArray();
                var evidence = cards.Select(p => CardNumberComparer.Card2Int(p.Number)).ToList();

                // 'A' could be 14 and 1
                if (cards[0].Number == 'A')
                {
                    evidence.Add(1);
                }

                for (int i = 4, len = evidence.Count; i < len; i++)
                {
                    if (evidence[i - 4] - evidence[i] == 4)
                    {
                        var rs = new StraightGameResult();
                        rs.Evidence = evidence.Skip(i - 4).Take(5).ToList();
                        rs.Cards = cards.Skip(i - 4).Take(5).ToList();
                        if (rs.Cards.Count == 4)
                        {
                            rs.Cards.Add(cards.First());
                        }
                        return rs;
                    }
                }
            }
            return null;
        }
    }

    public class StraightGameResult : GameResult
    {
        public override ResultLevel Level
        {
            get { return ResultLevel.Straight; }
        }

        public override string ToString()
        {
            return string.Format("Straight -> {0} {1} {2} {3} {4}", Cards[0], Cards[1], Cards[2], Cards[3], Cards[4]);
        }
    }
}